package com.message.Aliyun_ai_API.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class Aliyun_ai_imageUtil {
    public static void downloadImage(String imageUrl,String myPath, Integer userId, String taskId) throws IOException {//url图片保存到本地
        // 构造URL
        URL url = new URL(imageUrl);
        // 打开连接
        URLConnection con = url.openConnection();
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File file = new File(myPath);
        FileOutputStream os = new FileOutputStream(file, true);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }
    public static String getImageOfUrl(String myPath,String externalResourceDir){//将图片映射为url路径
        File file = new File(myPath);
        if (!file.exists() || !file.isFile()) {
            throw new IllegalArgumentException("找不到文件或文件为空: " + myPath);
        }

        // 获取文件相对于externalResourceDir的路径
        String relativePath = file.getAbsolutePath().substring(externalResourceDir.length());
        if (relativePath.startsWith(File.separator)) {
            relativePath = relativePath.substring(1);
        }

        relativePath = relativePath.replace(File.separatorChar, '/');
        // 对路径中的每个部分进行URL编码，但保留正斜杠
        String encodedPath = encodePath(relativePath);
        // 构建URL
        return "http://localhost:8081/" + encodedPath;
    }
    private static String encodePath(String path) {
        StringBuilder encodedPath = new StringBuilder();
        for (String part : path.split("/")) {
            if (encodedPath.length() > 0) {
                encodedPath.append('/');
            }
            try {
                encodedPath.append(URLEncoder.encode(part, StandardCharsets.UTF_8.toString()));
            } catch (Exception e) {
                throw new RuntimeException("无法映射对应文件 " + part, e);
            }
        }
        return encodedPath.toString();
    }
}
